import { Empty, Skeleton, Tabs } from 'antd';
import {
  CSSProperties, useEffect, useMemo, useRef, useState,
} from 'react';
import { SettingOutlined } from '@ant-design/icons';
import { showAsyncModal, udp, useRefState } from '@cscec/udp-ui';
import styles from './index.less';
import { getDataList as getDataListAPI, getRecentUseMeneList, saveOrUpdateBatch } from './service';
import { containerStyle } from '../common';
import { Content } from './components';
import { Card } from './components/Card';
import { HistoryMenuCard } from './components/HistoryMenuCard';
import React from 'react';

/**
 * 最常使用
 */
function InnerFc(props: { forceUpdate: object, setData: Function, env: any }) {
  const [state, setState] = useRefState({ loading: true, list: [] });

  const inUseList = useMemo(() => state.list?.filter((item: any) => item.useFlg === 1) ?? [], [state]);
  const getDataList = async () => {
    setState({ loading: true });
    const res = await getDataListAPI();
    if (res.code === 0) {
      props.setData(res.data || []);
      setState({
        loading: false,
        list: res.data,
      });
    }
  };
  useEffect(() => {
    getDataList();
  }, [props.forceUpdate]);

  if (state.loading) {
    return (
      <div className={styles.wrapper} style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(230px, 1fr))' }}>
        {new Array(5).fill(1).map((_, index) => (
          <div className={styles.item} key={index}>
            <Skeleton.Avatar className="hover-mask" active size={64} shape="square" style={{ marginLeft: 24 }} />
          </div>
        ))}
      </div>
    );
  }

  const len = inUseList.length;

  if (!len) {
    return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  }

  return (
    <div>
      <div className={styles.wrapper} style={{ gridTemplateColumns: `${len > 3 ? 'repeat(auto-fit, minmax(230px, 1fr))' : 'repeat(auto-fit, minmax(180px, 230px))'}` }}>
        {inUseList.map((item: any, index: any) => (
          <Card env={props.env} key={index} {...item} />
        ))}
      </div>
    </div>
  );
}

/**
 * 最近使用
 */
function HistoryMenu(props: { forceUpdate: object, env: any }) {
  const [state, setState] = useRefState({ loading: true, list: [] });

  const inUseList = useMemo(() => state.list ?? [], [state]);
  const getDataList = async () => {
    setState({ loading: true });
    const res = await getRecentUseMeneList();
    if (res.code === 0) {
      setState({
        loading: false,
        list: res.data,
      });
    }
  };
  useEffect(() => {
    getDataList();
  }, [props.forceUpdate]);

  if (state.loading) {
    return (
      <div className={styles.wrapper} style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(230px, 1fr))' }}>
        {new Array(5).fill(1).map((_, index) => (
          <div className={styles.item} key={index}>
            <Skeleton.Avatar className="hover-mask" active size={64} shape="square" style={{ marginLeft: 24 }} />
          </div>
        ))}
      </div>
    );
  }

  const len = inUseList.length;

  if (!len) {
    return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  }

  return (
    <div>
      <div className={styles.wrapper} style={{ gridTemplateColumns: `${len > 3 ? 'repeat(auto-fit, minmax(230px, 1fr))' : 'repeat(auto-fit, minmax(180px, 230px))'}` }}>
        {inUseList.map((item: any, index: any) => (
          <HistoryMenuCard env={props.env} key={index} {...item} />
        ))}
      </div>
    </div>
  );
}

export default function CommonFunction(props: IProps) {
  const {
    commonTitle, recentlyTitle, style, env,
  } = props;
  const [forceUpdate, setForceUpdate] = useState({});
  const [activeKey, setActiveKey] = useState('commonUse');
  const dataRef = useRef<{ list: any[], updateList: any[] }>({ list: [], updateList: [] });

  const items = [
    {
      key: 'commonUse',
      label: commonTitle || '最常使用',
      children: <InnerFc env={env} forceUpdate={forceUpdate} setData={(data: any[]) => { dataRef.current.list = data; }} />,
    },
    {
      key: 'recentUse',
      label: recentlyTitle || '最近使用',
      children: <HistoryMenu env={env} forceUpdate={forceUpdate}/>,
    },
  ];

  const showSetting = async () => {
    if (env.session !== 'render') {
      udp.message('预览时不能进行设置操作!');
      return;
    }
    await showAsyncModal({
      title: '常用功能设置',
      width: 1000,
      height: 600,
      autoDestroy: true,
      async beforeResolve(isOk) {
        if (isOk) {
          if (dataRef.current.updateList?.length) {
            const { code, message } = await saveOrUpdateBatch(dataRef.current.updateList);
            if (code !== 0) {
              udp.message(message);
              return false;
            }
            setForceUpdate({});
          }
        }
        return true;
      },
      content: <Content dataRef={dataRef} />,
    });
  };

  return (
    <div style={{ ...containerStyle, ...style, paddingTop: 0 }}>
      <Tabs
        activeKey={activeKey}
        onChange={setActiveKey}
        items={items}
        tabBarExtraContent={activeKey === 'commonUse' ? <SettingOutlined key="setting" style={{ cursor: 'pointer' }} onClick={showSetting} /> : null}
      />
    </div>
  );
}

export interface IProps {
  commonTitle: string;
  recentlyTitle: string;
  style?: CSSProperties;
  [x: string]: any;
}
